#!/usr/bin/env python
# -*-coding: utf8 -*-
'''
# created by: iori
# created on: Wed 11 Dec 2013 02:21:48 PM CST
'''
import argparse
import os
import logging
import threadpool
from pcs import get_pcs

logger = logging.getLogger(__name__)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('dir', help='directory to backup ')
    parser.add_argument('-r', '--remote', help="remote directoy")
    parser.add_argument('-o', '--offset', type=int, default=1, help="remove how many level of source directory")
    parser.add_argument('-d', '--debug', action='store_true', default=False, help="just show which file will be transfered, not do real operations")
    parser.add_argument('-t', '--thread', action='store_true', default=False, help='to start multithread upload?')
    args = parser.parse_args()
#    print args
    if args.dir:
        pool = None
        if not args.debug:
            pcs = get_pcs()
            if args.thread:
                pool = threadpool.ThreadPool(5)
        # level of dir to remove from source
        offset = args.offset + 1 if args.dir.startswith('.') else args.offset
        for r, ds, fs in os.walk(args.dir):
            rt = r.replace('\\', '/').strip('/')
            rpath = args.remote
            # rt is like :  a/b , ./a/b, ../a/b
            pos = rt.replace('/', '*', offset-1).find('/')
            rt = '' if pos==-1 else rt[pos+1:]
            if rt:
                rt = rt.strip('/')
                rpath = rt if not rpath else '{0}/{1}'.format(rpath.strip('/'), rt.strip('/'))
            else:
                rpath = rpath.strip('/') if rpath else ''
            rdir = rpath
            for f in fs:
                rpath = '{0}/{1}'.format(rdir, f) if rdir else f
                lpath = os.path.join(r, f)
                logger.info(rpath)
                if not args.debug:
                    if pool:
                        pool.putRequest(threadpool.WorkRequest(pcs.save, [],{'data': lpath, 'path': rpath}))
                    else:
                        pcs.save(data=lpath, path=rpath)
        if pool:
            pool.wait()
if __name__ == '__main__':
    main()

